import 'dart:io';

import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:xcite/core/services/open_launcher.dart';
import 'package:xcite/core/utils/ali.dart';
import 'package:xcite/core/widgets/loading_widget.dart';

import '../../core/models/travel_log_model.dart';
import '../../core/providers/travel_log_provider.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/popup_helper.dart';
import '../../core/utils/toast_helper.dart';

class PublishTravelLogScreen extends ConsumerStatefulWidget {
  const PublishTravelLogScreen({super.key});

  @override
  ConsumerState<PublishTravelLogScreen> createState() =>
      _PublishTravelLogScreenState();
}

class _PublishTravelLogScreenState extends ConsumerState<PublishTravelLogScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final TextEditingController _contentController = TextEditingController();

  String? _selectedMediaPath;
  String? _videoCoverPath;
  bool _isPublishing = false;
  bool _isGeneratingThumbnail = false;
  TravelLogType _currentType = TravelLogType.image;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        setState(() {
          _currentType =
              _tabController.index == 0
                  ? TravelLogType.image
                  : TravelLogType.video;
          _selectedMediaPath = null;
          _videoCoverPath = null;
        });
      }
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    _contentController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg_2.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child:
              [
                _buildTopBar(),
                _buildTabBar(),
                Expanded(child: _buildMainContent()),
              ].toColumn(),
        ),
      ),
    );
  }

  Widget _buildTopBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child:
          [
            Container(
              width: 30.w,
              height: 30.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.black,
              ),
              child:
                  Icon(
                    Icons.arrow_back_ios_new,
                  ).iconSize(20.sp).iconColor(Colors.white).center(),
            ).inkWell(onTap: () => GoRouter.of(context).pop()),
            Spacer(),
            Text('Release')
                .fontSize(24.sp)
                .fontWeight(FontWeight.bold)
                .textColor(Colors.black)
                .fontFamily('PoetsenOne'),
            Spacer(),
            SizedBox(width: 36.w),
          ].toRow(),
    );
  }

  Widget _buildTabBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
      child: [
        _buildTabItem(0, 'assets/resources/picture.png'),
        SizedBox(width: 40.w),
        _buildTabItem(1, 'assets/resources/video.png'),
      ].toRow(mainAxisAlignment: MainAxisAlignment.center),
    );
  }

  Widget _buildTabItem(int index, String imagePath) {
    final isSelected = _tabController.index == index;
    final imageWidth = index == 0 ? 82.w : 62.w;

    return [
      Opacity(
        opacity: isSelected ? 1.0 : 0.6,
        child: Container(
          width: imageWidth,
          height: 30.w,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(imagePath),
              fit: BoxFit.contain,
            ),
          ),
        ),
      ),
      if (isSelected)
        Container(
          width: imageWidth,
          height: 8.h,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/resources/select.png'),
              fit: BoxFit.contain,
            ),
          ),
        )
      else
        SizedBox(height: 8.h),
    ].toColumn().inkWell(
      onTap: () {
        _tabController.animateTo(index);
      },
    );
  }

  Widget _buildMainContent() {
    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child:
          [
            _buildMediaSelector(),
            SizedBox(height: 24.h),
            _buildContentInput(),
            SizedBox(height: 40.h),
            _buildPublishButton(),
            SizedBox(height: 20.h),
            _buildEulaLink(),
            SizedBox(height: 40.h),
          ].toColumn(),
    );
  }

  Widget _buildMediaSelector() {
    return AspectRatio(
      aspectRatio: 374 / 314,
      child: Container(
        decoration: BoxDecoration(
          image:
              _selectedMediaPath == null
                  ? DecorationImage(
                    image: AssetImage(
                      'assets/resources/travel_log_image_input.png',
                    ),
                    fit: BoxFit.fill,
                  )
                  : (_currentType == TravelLogType.image
                      ? DecorationImage(
                        image: FileImage(File(_selectedMediaPath!)),
                        fit: BoxFit.cover,
                      )
                      : null),
          borderRadius: BorderRadius.circular(8.r),
        ),
        child:
            _selectedMediaPath == null
                ? Container(
                  width: 18.w,
                  height: 24.h,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/resources/add.png'),
                      fit: BoxFit.contain,
                    ),
                  ),
                ).center()
                : _currentType == TravelLogType.video
                ? Stack(
                  children: [
                    if (_videoCoverPath != null)
                      Positioned.fill(
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(8.r),
                          child: Image.file(
                            File(_videoCoverPath!),
                            fit: BoxFit.cover,
                          ),
                        ),
                      )
                    else
                      Positioned.fill(
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.grey[300],
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                          child:
                              _isGeneratingThumbnail
                                  ? [
                                    SizedBox(
                                      width: 24.w,
                                      height: 24.w,
                                      child: CircularProgressIndicator(
                                        strokeWidth: 2,
                                        valueColor:
                                            AlwaysStoppedAnimation<Color>(
                                              Colors.grey.shade600,
                                            ),
                                      ),
                                    ),
                                    SizedBox(height: 8.h),
                                    Text(
                                      'Generating thumbnail...',
                                      style: TextStyle(
                                        fontSize: 12.sp,
                                        color: Colors.grey.shade600,
                                      ),
                                    ),
                                  ].toColumn(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                  )
                                  : Icon(Icons.video_library)
                                      .iconSize(40.sp)
                                      .iconColor(Colors.grey.shade600)
                                      .center(),
                        ),
                      ),
                    Positioned.fill(
                      child:
                          Icon(AliIcons.iconPlayFill)
                              .iconSize(38.sp)
                              .iconColor(Colors.white.withValues(alpha: 0.8))
                              .center(),
                    ),
                  ],
                )
                : null,
      ).inkWell(onTap: _selectMedia),
    );
  }

  Widget _buildContentInput() {
    return AspectRatio(
      aspectRatio: 374 / 134,
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/travel_log_input.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: TextField(
          controller: _contentController,
          maxLines: null,
          expands: true,
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.black,
            fontFamily: 'PoetsenOne',
          ),
          decoration: InputDecoration(
            hintText: 'describe',
            hintStyle: TextStyle(
              fontSize: 16.sp,
              color: Colors.grey[600],
              fontFamily: 'PoetsenOne',
            ),
            border: InputBorder.none,
            contentPadding: EdgeInsets.all(20.w),
          ),
          textAlignVertical: TextAlignVertical.top,
        ),
      ),
    );
  }

  Widget _buildPublishButton() {
    return Container(
      width: double.infinity,
      height: 56.h,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/resources/log_release_button.png'),
          fit: BoxFit.fill,
        ),
      ),
      child:
          _isPublishing
              ? SizedBox(
                width: 24.w,
                height: 24.w,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
              ).center()
              : null,
    ).inkWell(onTap: _isPublishing ? null : _publishTravelLog);
  }

  Widget _buildEulaLink() {
    return Text(
      'EULA',
      style: TextStyle(
        fontSize: 16.sp,
        color: Colors.white,
        decoration: TextDecoration.underline,
        decorationColor: Colors.white,
      ),
    ).center().inkWell(
      onTap: () {
        Open.openLaunch(
          'https://www.freeprivacypolicy.com/live/2908db45-eaa5-4be2-bf12-428f9bbadb26',
        );
      },
    );
  }

  Future<void> _selectMedia() async {
    try {
      final RequestType requestType =
          _currentType == TravelLogType.image
              ? RequestType.image
              : RequestType.video;

      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: requestType,
          textDelegate: AssetPickerTextDelegate(),
        ),
      );

      if (result != null && result.isNotEmpty) {
        final AssetEntity asset = result.first;
        final File? file = await asset.file;

        if (file != null) {
          final String localPath = await _copyMediaToLocal(file);

          if (_currentType == TravelLogType.video) {
            if (mounted) {
              setState(() {
                _isGeneratingThumbnail = true;
                _selectedMediaPath = localPath;
                _videoCoverPath = null;
              });
            }

            final String? coverPath = await _generateVideoThumbnail(localPath);

            if (mounted) {
              setState(() {
                _isGeneratingThumbnail = false;
                _videoCoverPath = coverPath;
              });

              if (coverPath == null) {
                ToastHelper.error(
                  'Failed to generate video thumbnail',
                  context: context,
                );
              }
            }
          } else {
            if (mounted) {
              setState(() {
                _selectedMediaPath = localPath;
              });
            }
          }
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to select media', context: context);
      }
    }
  }

  Future<String> _copyMediaToLocal(File sourceFile) async {
    final Directory appDir = await getApplicationDocumentsDirectory();
    final String fileName =
        '${DateTime.now().millisecondsSinceEpoch}${path.extension(sourceFile.path)}';
    final String localPath = path.join(appDir.path, 'travel_logs', fileName);

    final Directory targetDir = Directory(path.dirname(localPath));
    if (!await targetDir.exists()) {
      await targetDir.create(recursive: true);
    }

    final File targetFile = await sourceFile.copy(localPath);
    return targetFile.path;
  }

  Future<String?> _generateVideoThumbnail(String videoPath) async {
    try {
      final Directory appDir = await getApplicationDocumentsDirectory();
      final String thumbnailDir = path.join(
        appDir.path,
        'travel_logs',
        'thumbnails',
      );

      final Directory targetDir = Directory(thumbnailDir);
      if (!await targetDir.exists()) {
        await targetDir.create(recursive: true);
      }

      final videoFile = File(videoPath);
      if (!await videoFile.exists()) {
        return null;
      }

      try {
        final String? thumbnail = await VideoThumbnail.thumbnailFile(
          video: videoPath,
          thumbnailPath: thumbnailDir,
          imageFormat: ImageFormat.JPEG,
          maxWidth: 0,
          maxHeight: 0,
          timeMs: 1000,
          quality: 85,
        );

        if (thumbnail != null && thumbnail.isNotEmpty) {
          final thumbnailFile = File(thumbnail);
          if (await thumbnailFile.exists()) {
            final fileSize = await thumbnailFile.length();

            if (fileSize > 1024) {
              return thumbnail;
            } else {
              await thumbnailFile.delete().catchError((_) => thumbnailFile);
            }
          } else {}
        }
      } catch (pluginError) {}

      return null;
    } catch (e) {
      return null;
    }
  }

  Future<void> _publishTravelLog() async {
    if (_contentController.text.trim().isEmpty) {
      ToastHelper.error('Please enter description', context: context);
      return;
    }

    if (_selectedMediaPath == null) {
      ToastHelper.error(
        'Please select ${_currentType == TravelLogType.image ? 'image' : 'video'}',
        context: context,
      );
      return;
    }

    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) {
      PopupHelper.showLoginDialog(
        context,
        onLoginPressed: () {
          GoRouter.of(context).push('/login');
        },
        onCancelPressed: () {},
      );
      return;
    }

    setState(() {
      _isPublishing = true;
    });

    LoadingWidget.showFullScreen(context);

    await Future.delayed(const Duration(milliseconds: 2000));

    try {
      final travelLogNotifier = ref.read(travelLogProvider.notifier);
      final success = await travelLogNotifier.publishTravelLog(
        userId: currentUser.id,
        content: _contentController.text.trim(),
        logType: _currentType,
        mediaUrl: _selectedMediaPath!,
        videoCoverUrl: _videoCoverPath,
      );

      if (mounted) {
        if (success) {
          LoadingWidget.hide(context);
          ToastHelper.success(
            'Travel log published successfully!',
            context: context,
          );
          GoRouter.of(context).pop();
        } else {
          LoadingWidget.hide(context);
          ToastHelper.error('Failed to publish travel log', context: context);
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to publish travel log', context: context);
      }
    } finally {
      if (mounted) {
        setState(() {
          _isPublishing = false;
        });
      }
    }
  }
}
